#!/usr/bin/env python

"""Runner script for the Dingo development environment for wireless
sensor networks.

Usage: dingo [options]

Options:
  -h, --help            show this help message and exit
  -d DIR, --dir=DIR     project DIR to open
  --profile             generate profiling data for use with pstats module
  -p PLUGINS, --plugins=PLUGINS
                        Choose which plugins to activate. The following are
                        available: Debug,  null,  ADC Readings
  --radio=RADIO         Choose which Radio simulation models to use. The
                        following are available: Free Space,  Two Ray Ground
                        Reflection
  --routing=ROUTING     Choose which Routing simulation models to use. The
                        following are available: Flood router
  --adc=ADC             Choose which ADC simulation models to use. The
                        following are available: From Spreadsheet,  Random
                        Sequence Selection,  Random Gaussian,  Random Uniform
  --time=TIME           Choose which Time simulation models to use. The
                        following are available: CPU Time

"""

__author__  = "Sarah Mount"
__version__ = "1.0.1"
__date__    = "2008"

import Dingo.Main, Dingo.pluginManager, Dingo.modelManager
import os, string, sys

from optparse import OptionParser

def init_managers():
	"""Initialise plugin and model managers.

	@rtype: (Dingo.pluginManager.PluginManager, Dingo.modelManager.ModelManager)
	"""
	pm = Dingo.pluginManager.PluginManager(None, None, None)
	mm = Dingo.modelManager.ModelManager(None)

	return pm, mm

def create_parser():
	"""Setup command line parser.

	@rtype: OptionParser
	"""
    	parser = OptionParser()
	pm, mm = init_managers()
	
	# Load a project at startup
    	parser.add_option('-d', '--dir', dest='project', 
                      	  metavar='DIR', action='store',			
                      	  help='project DIR to open')

	# Turn profiling on / off
    	parser.add_option('--profile', dest='profile', 
                      	  action='store_true',
                      	  help='generate profiling data for use with pstats module')
	
	# Add options to load plugins at startup
 	helptxt = 'Choose which plugins to activate. The following are available:'
	names = pm.getPluginNames()
	for i in xrange(len(names)):
		if i < len(names) - 1:
			helptxt += ' ' + names[i] + ', '
		else: helptxt += ' ' + names[i]
	parser.add_option('-p', '--plugins', dest='plugins',
			  action='append', type='choice', metavar='PLUGINS',
			  choices=pm.getPluginNames(),
			  help=helptxt)

	# Add options to use the various models available
	model_d = mm.getAvailableModelsByType()	

	for modeltype in model_d:
	 	helptxt = ('Choose which ' + modeltype + ' simulation ' +
			   'models to use. The following are available:')
		for i in xrange(len(model_d[modeltype])):
			if i < len(model_d[modeltype]) - 1:
				helptxt += ' ' + model_d[modeltype][i] + ', '
			else: helptxt += ' ' + model_d[modeltype][i]
		parser.add_option('', '--'+string.lower(modeltype), dest='models',
				  action='append', type='choice', metavar=string.upper(modeltype),
				  choices=model_d[modeltype],
				  help=helptxt)

	# Set default options
	parser.set_defaults(profile=False)
	# Cleanup memory
	del pm
	del mm
	return parser


if __name__ == '__main__':
	parser = create_parser()

    	(options, args) = parser.parse_args()

	# TODO: Connect model options to models
	if options.models is not None:
		print 'Using the following Dingo models: (NOT IMPLEMENTED)'		
		for model in options.models:
			print '\t *', model
		print

	# TODO: Connect plugin options to plugins
	if options.plugins is not None:
		print 'Activating the following Dingo plugins: (NOT IMPLEMENTED)'
		for plugin in options.plugins:
			print '\t *', plugin
		print
	
	# Deal with opening a project directory
	if options.project and len(options.project) > 0:
		if not options.project.startswith(os.sep):
			project = os.getcwd() + os.sep + options.project
		else: project = options.project # Bah
		print 'Loading project:', project
	else: project = False

	# Turn on profiling
	if options.profile:
		import cProfile
		print 'Using Python profiler.'
		print 'Profiler output will be stored in dingo.prof in your project directory.'
		run = lambda x : cProfile.run("Dingo.Main._Run('" + project + "')",
			     		       os.getcwd() + os.sep + 'dingo.prof')
	else:
		run = lambda x: Dingo.Main._Run(project)

	parser.destroy()

	print
	run(None)
